const remove = require('lodash/remove');

// todo 超时机制判断，比如请求发出去3个小时以后才回来，应该被忽略
export default class RequestQueue {
  // 暂用数组来管理队列
  queue = [];

  resolve(requestId, ...args) {
    const request = this._getRequest(requestId);
    if (request) {
      request.resolve(...args);
      this.remove(requestId);
      return true;
    }
    return false;
  }

  reject(requestId, error) {
    const request = this._getRequest(requestId);
    if (request) {
      request.reject(error);
      this.remove(requestId);
      return true;
    }
    return false;
  }

  push(request) {
    this.queue.push(request);
  }

  remove(requestId) {
    console.log('todo 从队列中移除 ', requestId);
    remove(this.queue, (n) => n.requestId === requestId);
  }

  _getRequest(requestId) {
    return this.queue.find((req) => req.requestId === requestId);
  }

  getRequest(requestId) {
    return (this._getRequest(requestId) || {}).request;
  }
}
